<template>
  <div class="merchant-dashboard">
    <div class="dashboard-header">
      <div class="header-content">
        <div class="header-left">
          <h1>商户数据概览</h1>
          <p>欢迎回来，{{ userInfo?.name }}！这里是您的商户数据概览</p>
        </div>
        <div class="header-actions">
          <a-button type="primary" @click="refreshData" :loading="refreshing">
            <ReloadOutlined />
            刷新数据
          </a-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <a-card class="stat-card" :loading="loading">
        <div class="stat-content">
          <div class="stat-icon course-icon">
            <BookOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalCourses }}</div>
            <div class="stat-label">总课程数</div>
            <div class="stat-trend" :class="stats.courseTrend > 0 ? 'positive' : 'negative'">
              <ArrowUpOutlined v-if="stats.courseTrend > 0" />
              <ArrowDownOutlined v-else />
              {{ Math.abs(stats.courseTrend) }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card" :loading="loading">
        <div class="stat-content">
          <div class="stat-icon order-icon">
            <ShoppingCartOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalOrders }}</div>
            <div class="stat-label">总订单数</div>
            <div class="stat-trend" :class="stats.orderTrend > 0 ? 'positive' : 'negative'">
              <ArrowUpOutlined v-if="stats.orderTrend > 0" />
              <ArrowDownOutlined v-else />
              {{ Math.abs(stats.orderTrend) }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card" :loading="loading">
        <div class="stat-content">
          <div class="stat-icon student-icon">
            <UserOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">{{ stats.totalStudents }}</div>
            <div class="stat-label">总学员数</div>
            <div class="stat-trend" :class="stats.studentTrend > 0 ? 'positive' : 'negative'">
              <ArrowUpOutlined v-if="stats.studentTrend > 0" />
              <ArrowDownOutlined v-else />
              {{ Math.abs(stats.studentTrend) }}%
            </div>
          </div>
        </div>
      </a-card>

      <a-card class="stat-card" :loading="loading">
        <div class="stat-content">
          <div class="stat-icon income-icon">
            <DollarOutlined />
          </div>
          <div class="stat-info">
            <div class="stat-number">¥{{ stats.totalIncome }}</div>
            <div class="stat-label">总收入</div>
            <div class="stat-trend" :class="stats.incomeTrend > 0 ? 'positive' : 'negative'">
              <ArrowUpOutlined v-if="stats.incomeTrend > 0" />
              <ArrowDownOutlined v-else />
              {{ Math.abs(stats.incomeTrend) }}%
            </div>
          </div>
        </div>
      </a-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-card title="近7天订单趋势" class="chart-card" :loading="chartLoading">
            <div class="chart-container">
              <div ref="orderChartRef" class="chart" style="height: 300px;"></div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="课程分类分布" class="chart-card" :loading="chartLoading">
            <div class="chart-container">
              <div ref="categoryChartRef" class="chart" style="height: 300px;"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 最近订单 -->
    <a-card title="最近订单" class="recent-orders" :loading="loading">
      <template #extra>
        <a-button type="link" @click="viewAllOrders">查看全部</a-button>
      </template>
      <a-table 
        :columns="orderColumns" 
        :data-source="recentOrders" 
        :pagination="false"
        :scroll="{ x: 800 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'amount'">
            <span class="price">¥{{ record.amount }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewOrderDetail(record)">
                查看详情
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 快捷操作 -->
    <a-card title="快捷操作" class="quick-actions">
      <a-row :gutter="16">
        <a-col :span="6" :xs="12" :sm="6">
          <a-button type="primary" block @click="createCourse" class="action-btn">
            <PlusOutlined />
            创建课程
          </a-button>
        </a-col>
        <a-col :span="6" :xs="12" :sm="6">
          <a-button block @click="uploadMedia" class="action-btn">
            <CloudUploadOutlined />
            上传媒资
          </a-button>
        </a-col>
        <a-col :span="6" :xs="12" :sm="6">
          <a-button block @click="viewOrders" class="action-btn">
            <OrderedListOutlined />
            查看订单
          </a-button>
        </a-col>
        <a-col :span="6" :xs="12" :sm="6">
          <a-button block @click="shopSettings" class="action-btn">
            <SettingOutlined />
            店铺设置
          </a-button>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import * as echarts from 'echarts'
import {
  BookOutlined,
  ShoppingCartOutlined,
  UserOutlined,
  DollarOutlined,
  PlusOutlined,
  CloudUploadOutlined,
  OrderedListOutlined,
  SettingOutlined,
  ReloadOutlined,
  ArrowUpOutlined,
  ArrowDownOutlined
} from '@ant-design/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const userInfo = computed(() => authStore.userInfo)

// 状态管理
const loading = ref(false)
const refreshing = ref(false)
const chartLoading = ref(false)

// 图表引用
const orderChartRef = ref<HTMLElement>()
const categoryChartRef = ref<HTMLElement>()

// 统计数据
const stats = ref({
  totalCourses: 12,
  totalOrders: 156,
  totalStudents: 89,
  totalIncome: '12,580',
  courseTrend: 15,
  orderTrend: 8,
  studentTrend: 12,
  incomeTrend: 25
})

// 订单表格列定义
const orderColumns = [
  {
    title: '订单号',
    dataIndex: 'orderNo',
    key: 'orderNo',
    width: 120
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
    key: 'courseName',
    width: 200
  },
  {
    title: '学员',
    dataIndex: 'studentName',
    key: 'studentName',
    width: 100
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
]

// 最近订单数据
const recentOrders = ref([
  {
    key: '1',
    orderNo: 'ORD2024001',
    courseName: 'AI基础入门课程',
    studentName: '张三',
    amount: 299,
    status: 'paid',
    createTime: '2024-01-15 10:30:00'
  },
  {
    key: '2',
    orderNo: 'ORD2024002',
    courseName: '机器学习实战',
    studentName: '李四',
    amount: 599,
    status: 'completed',
    createTime: '2024-01-14 15:20:00'
  },
  {
    key: '3',
    orderNo: 'ORD2024003',
    courseName: '深度学习进阶',
    studentName: '王五',
    amount: 899,
    status: 'refunded',
    createTime: '2024-01-13 09:15:00'
  }
])

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    paid: 'green',
    completed: 'blue',
    refunded: 'red',
    pending: 'orange'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    paid: '已支付',
    completed: '已完成',
    refunded: '已退款',
    pending: '待处理'
  }
  return textMap[status] || '未知'
}

// 初始化订单趋势图表
const initOrderChart = () => {
  if (!orderChartRef.value) return
  
  const chart = echarts.init(orderChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月9日', '1月10日', '1月11日', '1月12日', '1月13日', '1月14日', '1月15日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '订单数',
        type: 'line',
        smooth: true,
        data: [12, 15, 18, 22, 19, 25, 28],
        itemStyle: {
          color: '#1890ff'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => chart.resize())
}

// 初始化分类分布图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) return
  
  const chart = echarts.init(categoryChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '课程分类',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 35, name: 'AI技术' },
          { value: 25, name: '编程开发' },
          { value: 20, name: '设计创意' },
          { value: 15, name: '数据科学' },
          { value: 5, name: '其他' }
        ]
      }
    ]
  }
  chart.setOption(option)
  
  // 响应式处理
  window.addEventListener('resize', () => chart.resize())
}

// 刷新数据
const refreshData = async () => {
  refreshing.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    // 这里可以调用真实的API
    console.log('数据已刷新')
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    refreshing.value = false
  }
}

// 快捷操作
const createCourse = () => {
  router.push('/merchant/course/create')
}

const uploadMedia = () => {
  router.push('/merchant/media/upload')
}

const viewOrders = () => {
  router.push('/merchant/orders')
}

const shopSettings = () => {
  router.push('/merchant/settings')
}

const viewAllOrders = () => {
  router.push('/merchant/orders')
}

const viewOrderDetail = (record: any) => {
  console.log('查看订单详情:', record)
  // 这里可以实现查看订单详情的逻辑
}

// 组件挂载时初始化
onMounted(async () => {
  loading.value = true
  chartLoading.value = true
  
  try {
    // 模拟加载数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 等待DOM更新后初始化图表
    await nextTick()
    initOrderChart()
    initCategoryChart()
    
  } catch (error) {
    console.error('初始化失败:', error)
  } finally {
    loading.value = false
    chartLoading.value = false
  }
})
</script>

<style scoped>
.merchant-dashboard {
  padding: 0;
}

.dashboard-header {
  margin-bottom: 32px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
}

.header-left h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 600;
}

.header-left p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.header-actions {
  flex-shrink: 0;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.stat-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
  flex-shrink: 0;
}

.course-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.order-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.student-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.income-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

.stat-trend.positive {
  color: #52c41a;
}

.stat-trend.negative {
  color: #ff4d4f;
}

.charts-section {
  margin-bottom: 32px;
}

.chart-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.chart-container {
  padding: 16px 0;
}

.chart {
  width: 100%;
}

.recent-orders {
  margin-bottom: 32px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.quick-actions {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.action-btn {
  height: 48px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
}

.price {
  color: #f5222d;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  }
}

@media (max-width: 768px) {
  .dashboard-header {
    margin-bottom: 24px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-left h1 {
    font-size: 24px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .charts-section .ant-col {
    margin-bottom: 16px;
  }
  
  .action-btn {
    height: 40px;
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .stat-icon {
    width: 56px;
    height: 56px;
    font-size: 24px;
  }
  
  .stat-number {
    font-size: 28px;
  }
}
</style>
